package org.xbmc.android.xbmcremote;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.Window;
import android.view.WindowManager;
import android.view.OrientationListener;
import android.widget.AbsoluteLayout;
import android.widget.ImageView;

/**
 * Main Remote TouchPad Activity
 * @author Stefan Agner
 *
 */
public class XBMCRemote extends Activity {
	private XBMCApplication oXBMCApplication;
	private XBMCOrientationListener oXBMCOrientationListener;
	
	private static final int ORIENTATION_PORTRAIT_UNKNOWN = 1;
	private static final int ORIENTATION_PORTRAIT_NORMAL = 1;
	private static final int ORIENTATION_LANDSCAPE_NORMAL = 2;
	private static final int ORIENTATION_PORTRAIT_UPSIDEDOWN = 3;
	private static final int ORIENTATION_LANDSCAPE_UPSIDEDOWN = 4;
	
	private static final int MENU_SETTINGS = 0;
	

	private int currentOrientation = ORIENTATION_PORTRAIT_NORMAL;
	private int currentPhysicalOrientation = ORIENTATION_PORTRAIT_UNKNOWN;
	private boolean orientationFixed = false;
    private float x = 0;
    private float y = 0;
    private long pressedTime;
	private float orientationX = 1;
	private float orientationY = 1;
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        

        if(savedInstanceState != null)
        {
        	currentOrientation = savedInstanceState.getInt("currentOrientation");
        	currentPhysicalOrientation = savedInstanceState.getInt("currentPhysicalOrientation");
            orientationFixed = savedInstanceState.getBoolean("orientationFixed");
        }
        
        // Set Window to be a fullscreen window...
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(org.xbmc.android.xbmcremote.R.layout.main);
        
        // Change the Position of the XBMC-Logo dynmaically (center...)
        DisplayMetrics dm = new DisplayMetrics(); 
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        ImageView oBackground  = (ImageView)findViewById(R.id.background);
        oBackground.setAlpha(100);
        if(currentOrientation == ORIENTATION_LANDSCAPE_NORMAL || currentOrientation == ORIENTATION_PORTRAIT_NORMAL)
        	oBackground.setImageDrawable(getResources().getDrawable(R.drawable.xbmc));
        else
        	oBackground.setImageDrawable(getResources().getDrawable(R.drawable.xbmcupsidedown));
        oBackground.setLayoutParams(new AbsoluteLayout.LayoutParams(210,140, dm.widthPixels/2-210/2, dm.heightPixels/2-140/2));

        // Create the Orientation Listener
        oXBMCOrientationListener = new XBMCOrientationListener(this);
        
        
    }


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		boolean result = super.onCreateOptionsMenu(menu);
		menu.add(0, MENU_SETTINGS, 0, R.string.settings).setIcon(android.R.drawable.ic_menu_preferences);
		
		return result;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		Intent i = null;
		
		switch (item.getItemId()) {

		case MENU_SETTINGS:
			i = new Intent(this, WifiConnectionSettings.class);
			startActivityForResult(i, MENU_SETTINGS);
			return true;
		default:
			return false;
		}
	}
	
    @Override
    public void onStart()
    {
    	super.onStart();
    	System.err.println("onStart");
    	
        oXBMCApplication = (XBMCApplication)getApplication();
        oXBMCApplication.setActivityRunning(true);
        oXBMCApplication.showCurrentState();
        
		//oXBMCClient.sendNotification("Android", "XBMC Remote for Android started...");
    	oXBMCOrientationListener.enable();
    	
    }

    @Override
    public boolean onTouchEvent(MotionEvent event)
    {	
    	if(event.getAction() == MotionEvent.ACTION_DOWN)
    	{
    		x = event.getX();
    		y = event.getY();
    		pressedTime = System.currentTimeMillis();
    	}
    	if(event.getAction() == MotionEvent.ACTION_MOVE)
    	{
    		float xDiff = (x - event.getX())*120.0f;
    		float yDiff = (y - event.getY())*120.0f;
    		oXBMCApplication.touchDifference((int)(xDiff * orientationX), (int)(yDiff * orientationY));
			x = event.getX();
			y = event.getY();
    	}
    	if(event.getAction() == MotionEvent.ACTION_UP)
    	{
    		long pressednow = System.currentTimeMillis(); 
    		if((pressednow - pressedTime) < 100)
    		{
    			// Pressed event...
    			oXBMCApplication.processTouchPress();
    		}
    	}
    	
    	return true;
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    	System.err.println(keyCode);
    	return oXBMCApplication.processKeyDown(keyCode);
    }
    
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
    	return oXBMCApplication.processKeyUp(keyCode);
    }
    
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
    	super.onConfigurationChanged(newConfig);
    	if((newConfig.keyboardHidden & Configuration.KEYBOARDHIDDEN_NO) == Configuration.KEYBOARDHIDDEN_NO)
    	{
    		changeOrientation(ORIENTATION_LANDSCAPE_NORMAL);
    		orientationFixed = true;
    	}
    	else
    	{
    		orientationFixed = false;
    		changeOrientation(ORIENTATION_LANDSCAPE_NORMAL);
    	}
    	
    }
    
    /**
     * Self implemented Orientation change
     * @param newOrientation Orientation defined in this class (ORIENTATION_XX)
     * @return 
     */
    public void changeOrientation(int newOrientation)
    {
    	if(orientationFixed)
    		return;
    	switch(newOrientation)
    	{
	    	case ORIENTATION_PORTRAIT_NORMAL:
				// Portrait normal
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
				currentOrientation = ORIENTATION_PORTRAIT_NORMAL;
				orientationX = 1.0f;
				orientationY = 1.0f;
				break;
	    	case ORIENTATION_LANDSCAPE_NORMAL:
				// Landscape Normal
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
				currentOrientation = ORIENTATION_LANDSCAPE_NORMAL;
				orientationX = 1.0f;
				orientationY = 1.0f;
				break;
	    	case ORIENTATION_PORTRAIT_UPSIDEDOWN:
				// Portrait upside down
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
				currentOrientation = ORIENTATION_PORTRAIT_UPSIDEDOWN;
				orientationX = -1.0f;
				orientationY = -1.0f;
				break;
	    	case ORIENTATION_LANDSCAPE_UPSIDEDOWN:
				// Landscape upside down
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
				currentOrientation = ORIENTATION_LANDSCAPE_UPSIDEDOWN;
				orientationX = -1.0f;
				orientationY = -1.0f;
				break;
			default:
				Log.e("XBMCRemote", "Invalid Orientation");
    	}
    }
    
    
    @Override
    public void onSaveInstanceState(Bundle outState)
    {
    	outState.putInt("currentOrientation", currentOrientation);
    	outState.putInt("currentPhysicalOrientation", currentPhysicalOrientation);
    	outState.putBoolean("orientationFixed", orientationFixed);
    }
    
    @Override
    protected void onPause() {
    	super.onPause();
        oXBMCApplication.setActivityRunning(false);
    }
    
    @Override
    public void onStop()
    {
    	super.onStop();
    	System.err.println("onStop");
    	oXBMCOrientationListener.disable();
    }
    

    @Override
    public void onDestroy()
    {
    	super.onDestroy();
    	System.err.println("onDestroy");
    }

    /**
     * Orientation Listener for the Touch direction. This way it is possible to use 
     * the Touchpad for any orientation (even upside down...) 
     * @author Stefan Agner
     *
     */
	class XBMCOrientationListener extends OrientationListener 
	{
		public XBMCOrientationListener(Context context) {
			super(context);
		}

		@Override
		public void onOrientationChanged(int orientation) {
			// Change orientation of this activity based on the Orientation sensor...
			if(orientation<=45 || orientation>315)
				currentPhysicalOrientation = ORIENTATION_PORTRAIT_NORMAL;
			else if(orientation<=315 && orientation>225)
				currentPhysicalOrientation = ORIENTATION_LANDSCAPE_NORMAL;
			else if(orientation<=225 && orientation>135)
				currentPhysicalOrientation = ORIENTATION_PORTRAIT_UPSIDEDOWN;
			else if(orientation<=135 && orientation>45)
				currentPhysicalOrientation = ORIENTATION_LANDSCAPE_UPSIDEDOWN;
			else 
				currentPhysicalOrientation = ORIENTATION_UNKNOWN;
			if(currentOrientation!=currentPhysicalOrientation)
				changeOrientation(currentPhysicalOrientation);
		}
		
	}
    
    
}